import java.io.*;
import java.text.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.ServletRequestWrapper;
import java.net.*;
//import java.security.Security;
//import java.security.Provider;
//import javax.net.ssl.*;

/**
 * The index servlet
 *
 * @author William Li
 */

public class IndexServlet extends HttpServlet {


    public void doGet(HttpServletRequest request,
                      HttpServletResponse response)
        throws IOException, ServletException
    {
	return;
	//doPost(request, response);
    }


    public void doPost(HttpServletRequest request, 
		       HttpServletResponse response)
    throws IOException, ServletException
    {
        response.setContentType("text/html");

        PrintWriter out = response.getWriter();

	Hashtable ps_hashtable = new Hashtable ();
	String page_head = request.getHeader("Referer");
	String rm_user   = request.getRemoteUser();
	String user_name = request.getParameter("user_name");
	String pass_word = request.getParameter("pass_word");
	String auth_type = request.getAuthType();

	PasswdFileLoader ps_file_loader = new PasswdFileLoader();
	ps_file_loader.setFileName(new File("D:/Apache2_Passwd/passwd", ".htaccess3"));
	ps_file_loader.loadFile();
	ps_hashtable = ps_file_loader.getHashtable();

	if (ps_hashtable.containsKey(user_name)) {

	    httpConnecter c = new httpConnecter ();

	    c.setUrl("http://192.168.1.101/_user/~"+user_name);
	    c.setUserName(user_name);
	    System.out.println("UserName"+user_name);
	    c.setPassWord(pass_word);
	    System.out.println("Password"+pass_word);
	    c.connecting();

	    String conn_message   = c.getConnMessage();
	    String return_message = c.getReturnMessage();
	
	    out.println("<!page_head="+page_head+">");

	    if ( (page_head.startsWith("http://66.167.8.223")||page_head.startsWith("http://192.168.1.101")) &&
		 (conn_message.equals("ResponseCode=200ResponseMessage=OK"))) {
		out.println("Welcome "+user_name);
		//ServletRequestWrapper sr = new ServletRequestWrapper(request);
		//System.out.println(sr.getContentType());
		//RequestDispatcher rd = request.getRequestDispatcher("/"); 
		//rd.forward(request,response);

	    }
	    else {
		out.println("passwd is invalied");
		out.println(conn_message);
		out.println(return_message);

		return;
	    }
	}
	else {
	    out.println("new user sign up page");
	    out.println(ps_hashtable);
	    return;
	}
    }

}






